<template>
  <!-- 单体电压趋势 -->
  <div class="chartContent">
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      ref="formRef"
      class="chartForm"
    >
      <a-form-item label="日期" name="code">
        <a-date-picker
          v-model:value="form.date"
          placeholder="选择日期"
          class="formSelect"
          formatter="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :allowClear="false"
        />
      </a-form-item>
      <a-form-item label="电池堆">
        <a-select
          ref="select"
          v-model:value="form.linkId"
          class="formInput"
          allow-clear
          placeholder="请选择"
          @change="changeLink"
        >
          <a-select-option
            v-for="item in energyLinkList"
            :value="item.deviceId"
            :key="item.deviceId"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="电池簇">
        <a-select
          ref="select"
          v-model:value="form.equipId"
          class="formInput"
          allow-clear
          placeholder="请选择"
        >
          <a-select-option
            v-for="item in blockList"
            :value="item.deviceId"
            :key="item.deviceId"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-button
        type="primary"
        class="filterBtn"
        @click="handleFilter"
        :loading="chartLoading"
        >查询</a-button
      >
    </a-form>
    <a-spin :spinning="chartLoading">
      <div class="chartContainer" ref="voltageTrendChartRef"></div>
    </a-spin>
  </div>
  <!-- 查看数据 -->
  <DetailsData
    :detailsDataVisible="detailsDataVisible"
    :chartsTableData="chartsTableData"
    @update:detailsDataVisible="(val) => (detailsDataVisible = val)"
  />
</template>
<script setup>
;
import { commonConfigStore } from "@/stores/commonConfig";
import * as echarts from "echarts";
import { getVoltageDistributionOption } from "./chartOption";
import { getCurrentDate, getYesterdayFromDate } from "@/utils/common";

const props = defineProps({
  stationInfo: {
    type: Number,
  },
});
const $api = inject("$api");
const form = ref({
  date: null,
  linkId: null,
  equipId: null,
});
const voltageTrendChartRef = ref(null);
const voltageChart = ref(null);
const chartsData = ref([]);
const energyLinkList = ref([]);
const blockList = ref([]);
const chartLoading = ref(false);
const detailsDataVisible = ref(false);
const chartsTableData = ref([]);

// 表单验证规则
const rules = ref({});

const getEnergyLinkList = async () => {
  // 获取电池堆列表 如果不是主电池堆，需要拉取电池堆列表指定所属
  const res = await $api.energyLinkList({
    current: 1,
    size: 10000,
    stationId: props.stationInfo.id,
  });
  energyLinkList.value = res?.data;
  if (energyLinkList.value.length > 0) {
    form.value.linkId = energyLinkList.value[0].deviceId;
    await getBlockList(form.value.linkId);
  }
};
onUnmounted(() => {
  if (voltageChart.value) {
    voltageChart.value.dispose();
  }
  window.removeEventListener("resize", handleResize);
});

// 窗口大小变化处理
const handleResize = () => {
  if (voltageChart.value) {
    voltageChart.value.resize();
  }
};

// 监听窗口大小变化
watch(
  () => voltageChart.value,
  (newChart) => {
    if (newChart) {
      window.addEventListener("resize", handleResize);
    }
  }
);

// 初始化图表
const initChart = () => {
  const chartInstance = echarts.init(voltageTrendChartRef.value);
  if (chartInstance) {
    chartInstance.resize();
    chartInstance.clear();
    const option = getVoltageDistributionOption();
    chartInstance.setOption(option);
    voltageChart.value = markRaw(chartInstance);
  }
};
// 切换电池堆
const changeLink = async (id) => {
  form.value.equipId = null;
  await getBlockList(id, false); // 切换电池堆时不自动加载数据，等用户手动查询
};
// 获取电压数据
const getVoltageData = async () => {
  if (!form.value.date) {
    message.warning("请选择日期");
    return;
  }
  if (!form.value.equipId) {
    // 不显示警告，因为可能是初始化阶段
    console.log("电池簇未选择，跳过数据加载");
    return;
  }
  chartLoading.value = true;
  if (form.value.equipId) {
    await getVoltageScope();
  }
  const params = {
    stationId: props.stationInfo.id,
    blockId: form.value.equipId,
    date: form.value.date,
  };
  const res = await $api.voltageTrend(params);
  chartLoading.value = false;
  if (res && res.code === 0) {
    const timeData = [];
    let seriesData = []; // 存储240个系列的数据

    // 为240个电芯初始化数据数组
    for (let i = 0; i < 240; i++) {
      seriesData.push([]);
    }
    // 生成24小时的时间数据
    for (let hour = 0; hour < 24; hour++) {
      for (let minute = 0; minute < 60; minute += 1) {
        // 每1分钟一个点
        const timeStr = `${hour.toString().padStart(2, "0")}:${minute
          .toString()
          .padStart(2, "0")}`;
        timeData.push(timeStr);
      }
    }
    res.data.forEach((item, timeIndex) => {
      if (item.value) {
        const parsedValue = JSON.parse(item.value);
        if (Array.isArray(parsedValue)) {
          // 将这个时间点的240个电芯数据分配到对应的系列中
          for (let cellIndex = 0; cellIndex < 240; cellIndex++) {
            if (seriesData[cellIndex]) {
              seriesData[cellIndex].push(parsedValue[cellIndex]);
            }
          }
        } else {
          console.warn(
            `第${timeIndex + 1}条数据的value数组长度不足240个:`,
            parsedValue?.length || 0
          );
          // 填充空数据
          for (let cellIndex = 0; cellIndex < 240; cellIndex++) {
            if (seriesData[cellIndex]) {
              seriesData[cellIndex].push(null);
            }
          }
        }
      } else {
        // 如果没有value数据，填充空数据
        for (let cellIndex = 0; cellIndex < 240; cellIndex++) {
          if (seriesData[cellIndex]) {
            seriesData[cellIndex].push(null);
          }
        }
      }
    });
    updateChart({ timeData, seriesData });
  }
};
// 更新图表
const updateChart = (data) => {
  if (!voltageChart.value) {
    console.warn("图表实例不存在，重新初始化");
    initChart();
    if (!voltageChart.value) return;
  }

  const option = getVoltageDistributionOption(data.timeData);
  // 以下不直接用...展开运算取最大最小值是因为性能问题
  let minValue = Infinity;
  let maxValue = -Infinity;

  data.seriesData.forEach((series) => {
    if (Array.isArray(series) && series.length > 0) {
      const validValues = series.filter(
        (v) => v !== 0 && v != null && !isNaN(v)
      );
      if (validValues.length > 0) {
        const seriesMin = Math.min(...validValues);
        const seriesMax = Math.max(...validValues);
        if (seriesMin < minValue) minValue = seriesMin;
        if (seriesMax > maxValue) maxValue = seriesMax;
      }
    }
  });

  // 设置Y轴范围，确保有合理的默认值
  if (minValue !== Infinity && maxValue !== -Infinity) {
    option.yAxis[0].min = Math.floor(minValue);
    option.yAxis[0].max = Math.ceil(maxValue);
  } else {
    // 设置默认的Y轴范围
    option.yAxis[0].min = 20;
    option.yAxis[0].max = 50;
  }
  // 为240个系列分配数据
  if (option.series && data.seriesData) {
    for (
      let i = 0;
      i < Math.min(option.series.length, data.seriesData.length);
      i++
    ) {
      option.series[i].data = data.seriesData[i] || [];
    }
  }
  const markAreaData = [];
  // 提取时间部分的函数（从 "2025-07-10 00:01:00" 提取 "00:01"）
  const extractTime = (dateTimeStr) => {
    const time = dateTimeStr.split(" ")[1];
    return time.substring(0, 5);
  };
  // 添加充电时间段
  if (timeRange.value && timeRange.value.chargeTimes) {
    timeRange.value.chargeTimes.forEach((chargeTime) => {
      // 计算时间区间长度（小时）
      const beginTime = new Date(chargeTime.beginTime);
      const endTime = new Date(chargeTime.endTime);
      const timeDiffHours = (endTime - beginTime) / (1000 * 60 * 60);
      // 只有当时间区间大于1小时时才显示"充电"字样
      const displayName = timeDiffHours > 1 ? "充电" : "";
      markAreaData.push([
        {
          name: displayName,
          xAxis: extractTime(chargeTime.beginTime),
          itemStyle: {
            color: "rgba(217, 0, 27, 0.09)",
            borderColor: "rgba(139, 69, 19, 0.6)",
            borderWidth: 1,
          },
        },
        {
          xAxis: extractTime(chargeTime.endTime),
        },
      ]);
    });
  }
  // 添加放电时间段
  if (timeRange.value && timeRange.value.dischargeTimes) {
   
    timeRange.value.dischargeTimes.forEach((dischargeTime) => {
       // 计算时间区间长度（小时）
      const beginTime = new Date(dischargeTime.beginTime);
      const endTime = new Date(dischargeTime.endTime);
      const timeDiffHours = (endTime - beginTime) / (1000 * 60 * 60);
      // 只有当时间区间大于1小时时才显示"放电"字样
      const displayName = timeDiffHours > 1 ? "放电" : "";
      markAreaData.push([
        {
          name: displayName,
          xAxis: extractTime(dischargeTime.beginTime),
          itemStyle: {
            color: "rgba(91, 143, 249, 0.09)",
            borderColor: "rgba(25, 25, 112, 0.6)",
            borderWidth: 1,
          },
        },
        {
          xAxis: extractTime(dischargeTime.endTime),
        },
      ]);
    });
  }
  option.series[0].markArea = {
    silent: true,
    label: {
      show: true,
      color: "#ffffff",
      fontSize: 12,
      fontWeight: "bold",
      textShadowColor: "rgba(0,0,0,0.8)",
      textShadowBlur: 2,
      textShadowOffsetX: 1,
      textShadowOffsetY: 1,
    },
    itemStyle: {
      color: "rgba(139, 69, 19, 0.2)",
      borderColor: "rgba(139, 69, 19, 0.6)",
      borderWidth: 1,
    },
    data: markAreaData,
  };
  voltageChart.value.setOption(option, true);
};

const getBlockList = async (id, autoLoad = true) => {
  const params = {
    stationId: props.stationInfo.id,
    linkId: id,
  };
  const res = await $api.powerBlockList(params);
  if (res && res.code === 0) {
    blockList.value = res.data;
    if (blockList.value.length > 0) {
      form.value.equipId = blockList.value[0].deviceId;
      // 只有在 autoLoad 为 true 且有日期时才自动加载数据
      if (autoLoad && form.value.date) {
        getVoltageData();
      }
    }
  }
};
const timeRange = ref([]);
const getVoltageScope = async () => {
  const params = {
    stationId: props.stationInfo.id,
    blockId: form.value.equipId,
    date: form.value.date,
  };
  const res = await $api.voltageScope(params);
  if (res && res.code === 0) {
    timeRange.value = res.data;
  }
};
const handleChageStation = async () => {
  form.value.date = getCurrentDate();
  await getEnergyLinkList();
};
const handleFilter = () => {
  getVoltageData();
};
defineExpose({ handleChageStation });
</script>

<style lang="less" scoped>
.chartForm {
  margin-top: 20px;
}
.ant-form-item {
  margin-bottom: 20px;
}
.formInput {
  width: 180px;
}
.chartContainer {
  margin-bottom: 20px;
  width: 100%;
  height: 400px;
  background: #141414;
  border-radius: 4px;
}
.filterBtn {
  margin-right: 20px;
}
</style>
